package com.gmail.hongyz.myfuse.dataengine;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

public class JsonRequestImpl implements JsonRequest {

	private JSONObject json;
	private Map<String, Dataset> datasetMap;
	private HttpServletRequest servletRequest;
	
	private void init() {
		datasetMap = new HashMap<String, Dataset>();
		JSONArray datasets = null;
		try {
			datasets = json.getJSONArray("datasets");
		} catch (JSONException e) {
			return ;
		}
		for (int i = 0; i < datasets.size(); i++) {
			String datasetId = datasets.getJSONObject(i).getString("datasetId");
			Dataset dataset = convertToDataset(datasets.getJSONObject(i));
			datasetMap.put(datasetId, dataset);
		}
	}
	public String getParameter(String parameter) {
		String value = null;
		try {
			value = json.getJSONObject("parameters").getString(parameter);
		} catch (JSONException e) {
		}
		return value;
	}

	public void setJson(JSONObject json) {
		this.json = json;
		init();
	}

	public Dataset getDataset(String datasetId) {
		return datasetMap.get(datasetId);
	}
	
	private Dataset convertToDataset(JSONObject jsonObject) {
		Dataset dataset = new Dataset();
//		Dataset dataset = (Dataset) JSONObject.toBean(jsonObject, Dataset.class);

		JSONArray jsRecords = jsonObject.getJSONArray("records");
		for (int i = 0; i < jsRecords.size(); i++) {
			JSONObject jsRecord = jsRecords.getJSONObject(i);
			Map<String, Object> map = new HashMap<String, Object>();
			for (Iterator iterator = jsRecord.keys(); iterator.hasNext();) {
				String key = (String) iterator.next();
				map.put(key, jsRecord.get(key));
			}
			Record record = new Record(map);
			int state = jsRecord.getInt("_state");
			record.setState(state);
			dataset.addRecord(record);
		}
		
		return dataset;
	}
	
	public JSONObject toJson() {
		return json;
	}
	@Override
	public String toString() {
		return toJson().toString();
	}
	public HttpServletRequest getServletRequest() {
		return servletRequest;
	}
	public void setServletRequest(HttpServletRequest servletRequest) {
		this.servletRequest = servletRequest;
	}
}
